import { useEffect, useRef, useState } from 'react';

export const useIsTextTruncated = () => {
  const [isTruncated, setIsTruncated] = useState(false);
  const textRef = useRef<HTMLSpanElement>(null);

  useEffect(() => {
    const checkTruncation = () => {
      if (textRef.current) {
        const element = textRef.current;
        const scrollWidth = element.scrollWidth;
        const clientWidth = element.clientWidth;
        const isTextTruncated = scrollWidth > clientWidth;

        console.log('Truncation check:', {
          scrollWidth,
          clientWidth,
          isTextTruncated,
          element: element.textContent?.substring(0, 50),
        });

        setIsTruncated(isTextTruncated);
      }
    };

    // 延迟检查，确保 DOM 完全渲染
    const timer = setTimeout(checkTruncation, 100);

    // 监听窗口大小变化
    window.addEventListener('resize', checkTruncation);

    return () => {
      clearTimeout(timer);
      window.removeEventListener('resize', checkTruncation);
    };
  }, []);

  return { isTruncated, textRef };
};
